<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Resources;

use App\Models\RoleMenuPermission;

/**
 * 角色管理模块资源
 * Class RoleResource
 * @package App\Http\Resources
 */
class RoleResource extends BaseResource
{
    /**
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        // 角色-菜单-权限数据
        $getRoleMenuPermission = RoleMenuPermission::where('role_id', $this->id)->get();
        $menu_permission_ids = [];
        collect($getRoleMenuPermission)->each(function ($item) use (&$menu_permission_ids) {
            if ($item['permission_id'] > 0) $menu_permission_ids[$item['menu_id']][] = $item['permission_id'];
            else $menu_permission_ids[$item['menu_id']] = [];
        });
        // 栏目权限数据
        $category_ids = collect($this->roleCategory)->map(function ($item) {
            return $item->info_category_id;
        })->toArray();
        return $this->filterFields([
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'sort' => $this->sort,
            'status' => $this->status,
            'menu_permission_ids' => $menu_permission_ids,
            'category_ids' => $category_ids,
            'created_at' => $this->created_at ? $this->created_at->format('Y-m-d H:i:s') : "",
            'updated_at' => $this->updated_at ? $this->updated_at->format('Y-m-d H:i:s') : "",
        ]);
    }
}
